package indi.qing.common;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.GeneralTextRequestBody;
import com.huaweicloud.sdk.ocr.v1.model.GeneralTextWordsBlockList;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeGeneralTextRequest;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeGeneralTextResponse;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class OrcUtils {

    public String getWords(String url){
        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();

        BasicCredentials basicCredentials = new BasicCredentials()
                .withAk(Constant.ak)
                .withSk(Constant.sk)
                .withProjectId(Constant.PROJECTID);

        // 指定终端节点，以OCR服务北京四的 endpoint 为例
        String endpoint = "https://ocr.cn-north-4.myhuaweicloud.com";

        // 初始化指定云服务的客户端 {Service}Client ，以初始化 Region 级服务OCR的 OcrClient 为例
        OcrClient ocrClient = OcrClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(basicCredentials)
                .withEndpoint(endpoint)
                .build();


        // 以调用通用表格识别接口 RecognizeGeneralTable 为例
        RecognizeGeneralTextRequest request = new RecognizeGeneralTextRequest();
        GeneralTextRequestBody body = new GeneralTextRequestBody();
        body.withUrl(url);
        request.withBody(body);
        AtomicReference<String> res = new AtomicReference<>("");
        try {
            RecognizeGeneralTextResponse response = ocrClient.recognizeGeneralText(request);
            List<GeneralTextWordsBlockList> wordsBlockList = response.getResult().getWordsBlockList();
            wordsBlockList.stream().forEach(word ->{
                res.set(res + word.getWords());
            });
            System.out.println(res);
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return String.valueOf(res);
    }
}
